import { ref } from 'vue'
import app from '@/app'
import { get, update, del, cover } from '@/api/store/goods'

import base from '@/app/model'

// 继承总模型
const model = new base;

model.getData().page_size = 20;

// 查询类型
model.where = ref({ key: 'number', value: '' })

// 生成查询数据
model.getWhere = () => {
  // 查询方式
  const where = { [model.where.value.key]: model.where.value.value }
  // 合并数据
  return Object.assign(where, model.getData())
}

model.get = () => {
  return new Promise((resolve, jeject) => {
    app.ui.loading()
    get(model.getWhere()).then(res => {
      model.setList(res.data)
      // 分页
      model.setData(Object.assign(model.getData(), {
        page: res.current_page,
        page_size: res.per_page,
        page_total: res.total
      }))
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      app.ui.loadingClose()
    })
  })
}

model.update = (...arge) => {
  return new Promise((resolve, jeject) => {
    update(...arge).then(res => {
      model.get()
      app.ui.message('success', res.message)
      resolve(res)
    }).catch(res => {
      app.ui.message('error', 'error.' + res.message)
      jeject(res)
    })
  })
}

model.updateName = (...arge) => {
  return new Promise((resolve, jeject) => {
    update(...arge).then(res => {
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

model.del = (...arge) => {
  return new Promise((resolve, jeject) => {
    del(...arge).then(res => {
      model.get()
      resolve(res)
    }).catch(res => {
      app.ui.message('error', 'error.' + res.message)
      jeject(res)
    })
  })
}

model.delete = (...arge) => {
  return new Promise((resolve) => {
    del(...arge).then(res => {
      resolve(res)
    })
  })
}

model.cover = (...arge) => {
  return new Promise((resolve, jeject) => {
    cover(...arge).then(res => {
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

// 查询未分类
model.getNoMenu = () => {
  return new Promise((resolve, jeject) => {
    get({ menu_id: 0, all: true, select: 'id' }).then(res => {
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

model.page = (page) => {
  model.getData().page = page
  model.get()
}

// 导出
model.excel = page => {
  return new Promise((resolve, jeject) => {
    // 查询
    get({page, menu_id: model.getData().menu_id}).then(res => {
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

export default model